<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input
        v-model="data.name"
        prefix-icon="Search"
        style="width: 240px; margin-right: 10px"
        placeholder="请输入宠物名称查询"
      ></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset"
        >重置</el-button
      >
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
        tooltip-effect="dark myTooltip"
        stripe
        :data="data.tableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <el-tabs
                v-model="activeName"
                class="demo-tabs"
                @tab-click="handleClick"
              >
                <el-tab-pane label="视频记录" name="first">
                  <el-table
                    :data="props.row.petCloudVideoList"
                    :border="childBorder"
                  >
                    <el-table-column label="动态视频" prop="url" width="300">
                      <template v-slot="scope">
                        <video
                          :src="scope.row.url"
                          controls
                          style="width: 100%; height: 150px"
                        ></video>
                      </template>
                    </el-table-column>
                    <el-table-column label="创建人" prop="createBy" />
                    <el-table-column label="创建时间" prop="createTime" />
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="健康记录" name="second">
                  <el-table
                    :data="props.row.petCloudHealthList"
                    :border="childBorder"
                  >
                    <el-table-column label="体温" prop="centigrade" />
                    <el-table-column label="体重" prop="weight" />
                    <el-table-column label="身高" prop="height" />
                    <el-table-column label="心率" prop="heartRate" />
                    <el-table-column label="创建人" prop="createBy" />
                    <el-table-column label="创建时间" prop="createTime" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="宠物名称"></el-table-column>
        <el-table-column prop="typeName" label="宠物类型"></el-table-column>
        <el-table-column prop="breed" label="宠物品种"></el-table-column>
        <el-table-column prop="sex" label="宠物性别"></el-table-column>
        <el-table-column prop="location" label="宠物所在地"></el-table-column>
        <el-table-column prop="photo" label="宠物图片">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 50px; border-radius: 5px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
              preview-teleported
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="云养金额"></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="primary" link @click="handleDynamic(scope.row)"
              >发布动态视频</el-button
            >
            <el-button type="primary" link @click="handleHealth(scope.row)"
              >健康记录</el-button
            >
            <el-button type="danger" link @click="del(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
        @current-change="load"
        background
        layout="total, prev, pager, next"
        :page-size="data.pageSize"
        v-model:current-page="data.pageNum"
        :total="data.total"
      />
    </div>

    <el-dialog
      title="宠物信息"
      v-model="data.formVisible"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="data.form"
        :rules="data.rules"
        label-width="90px"
        style="padding: 20px"
      >
        <el-form-item prop="name" label="宠物名称">
          <el-input
            v-model="data.form.name"
            placeholder="请输入宠物名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="type" label="宠物类型">
          <el-select style="width: 100%" v-model="data.form.typeId">
            <el-option
              v-for="item in data.typeList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="breed" label="宠物品种">
          <el-input
            v-model="data.form.breed"
            placeholder="请输入宠物品种"
          ></el-input>
        </el-form-item>
        <el-form-item prop="location" label="宠物所在地">
          <el-input
            v-model="data.form.location"
            placeholder="请输入宠物所在地"
          ></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="宠物性别">
          <el-radio-group v-model="data.form.sex">
            <el-radio-button label="公" value="公"></el-radio-button>
            <el-radio-button label="母" value="母"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="amount" label="云养金额">
          <el-input
            type="number"
            v-model="data.form.amount"
            placeholder="请输入云养金额"
          ></el-input>
        </el-form-item>
        <el-form-item prop="photo" label="宠物图片">
          <el-upload
            :action="baseUrl + '/files/upload'"
            :headers="{ token: data.user.token }"
            :on-success="handleFileUpload"
            list-type="picture"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 动态视频 -->
    <el-dialog
      title="发布动态视频"
      v-model="data.viewVisible"
      width="40%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="data.dynamicForm"
        :rules="data.rules"
        label-width="90px"
        style="padding: 20px"
      >
        <el-form-item prop="url" label="动态视频">
          <el-upload
            :action="baseUrl + '/files/upload'"
            :headers="{ token: data.user.token }"
            :on-success="handleFileUpload"
            list-type="video"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.viewVisible = false">关 闭</el-button>
          <el-button type="primary" @click="saveDynamic">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 健康记录 -->
    <el-dialog
      title="发布健康记录"
      v-model="data.viewVisibleHealth"
      width="40%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="data.healthForm"
        :rules="data.rules"
        label-width="90px"
        style="padding: 20px"
      >
        <el-form-item label="宠物体温" label-suffix="℃">
          <el-input-number
            v-model="data.healthForm.centigrade"
            :precision="2"
            :step="1"
          /><span style="margin-left: 10px; color: gray">℃</span>
        </el-form-item>
        <el-form-item label="宠物体重">
          <el-input-number
            v-model="data.healthForm.weight"
            :precision="2"
            :step="1"
          /><span style="margin-left: 10px; color: gray">kg</span>
        </el-form-item>
        <el-form-item label="宠物身高">
          <el-input-number
            v-model="data.healthForm.height"
            :precision="2"
            :step="1"
          /><span style="margin-left: 10px; color: gray">cm</span>
        </el-form-item>
        <el-form-item label="宠物心率">
          <el-input-number v-model="data.healthForm.heartRate" :step="1" /><span
            style="margin-left: 10px; color: gray"
            >次/分</span
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.viewVisibleHealth = false">关 闭</el-button>
          <el-button type="primary" @click="saveHealth">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { reactive, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const activeName = "first";
const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
  formVisible: false,
  formVisibleAudit: false,
  form: {},
  dynamicForm: {},
  healthForm: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  name: null,
  ids: [],
  shopList: [],
  typeList: [],
  rules: {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    typeId: [{ required: true, message: "请选择分类", trigger: "change" }],
    price: [{ required: true, message: "请输入价格", trigger: "blur" }],
    url: [{ required: true, message: "请上传视频", trigger: "blur" }],
  },
  viewVisible: false,
  viewVisibleHealth: false,
  content: null,
});

const formRef = ref();

const baseUrl = import.meta.env.VITE_BASE_URL;
const handleFileUpload = (res) => {
  data.form.photo = res.data;
  data.dynamicForm.url = res.data;
};

const view = (content) => {
  data.content = content;
  data.viewVisible = true;
};

/* wangEditor5 初始化开始 */
const editorRef = shallowRef(); // 编辑器实例，必须用 shallowRef
const mode = "default";
const editorConfig = { MENU_CONF: {} };
// 图片上传配置
editorConfig.MENU_CONF["uploadImage"] = {
  headers: {
    token: data.user.token,
  },
  server: baseUrl + "/files/wang/upload", // 服务端图片上传接口
  fieldName: "file", // 服务端图片上传接口参数
};
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor;
};
/* wangEditor5 初始化结束 */

request.get("/petShop/selectAll").then((res) => {
  data.shopList = res.data;
});

request.get("/petType/selectAll").then((res) => {
  data.typeList = res.data;
});

const load = () => {
  request
    .get("/petFostering/selectPage", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name,
        flag: "1",
      },
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data?.list || [];
        data.total = res.data?.total;
      } else {
        ElMessage.error(res.msg);
      }
    });
};
const handleAdd = () => {
  data.form = {
    sex: "公",
    status: "上架",
    recommend: "否",
    price: 100,
    shopId: data.user.id,
  };
  data.formVisible = true;
};
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

const handleAudit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisibleAudit = true;
};
const add = () => {
  request.post("/petFostering/add", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  request.put("/petFostering/update", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const recommend = (row, recommend) => {
  let form = JSON.parse(JSON.stringify(row));
  form.recommend = recommend;
  request.put("/petFostering/update", form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (!data.form.photo) {
        ElMessage.warning("请上传图片");
        return;
      }
      data.form.flag = 1;
      data.form.id ? update() : add();
    }
  });
};

const del = (id) => {
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  })
    .then((res) => {
      request.delete("/petFostering/delete/" + id).then((res) => {
        if (res.code === "200") {
          ElMessage.success("删除成功");
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch((err) => {
      console.error(err);
    });
};
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  })
    .then((res) => {
      request
        .delete("/petFostering/delete/batch", { data: data.ids })
        .then((res) => {
          if (res.code === "200") {
            ElMessage.success("操作成功");
            load();
          } else {
            ElMessage.error(res.msg);
          }
        });
    })
    .catch((err) => {
      console.error(err);
    });
};
const handleSelectionChange = (rows) => {
  data.ids = rows.map((v) => v.id);
};

const reset = () => {
  data.name = null;
  load();
};

load();
const audit = (status) => {
  data.form.auditStatus = status;
  request.put("/petFostering/audit", data.form).then((res) => {
    if (res.code == 200) data.formVisibleAudit = false;
    ElMessage.success("操作成功");
  });
};

const handleDynamic = (row) => {
  data.viewVisible = true;
  data.dynamicForm.petId = row.id;
};
const saveDynamic = () => {
  request.post("/pet/cloud/dynamic/add", data.dynamicForm).then((res) => {
    if (res.code == 200) {
      ElMessage.success("操作成功");
      load();
      data.viewVisible = false;
    }
  });
};
const handleHealth = (row) => {
  data.viewVisibleHealth = true;
  data.healthForm.petId = row.id;
}
const saveHealth = () => {
  request.post("/pet/cloud/health/add", data.healthForm).then((res) => {
    if (res.code == 200) {
      ElMessage.success("操作成功");
      load();
      data.viewVisibleHealth = false;
    }
  });
};
</script>
  
  <style>
.myTooltip {
  max-width: 40% !important;
}
</style>